package cn.dapeng.thread;

import cn.dapeng.util.SleepingUtil;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @BelongProject study
 * @BelongPackage cn.dapeng.thread
 * @Description TODO
 * @ClassName ThreadCommunicationT04
 * @Author xupenghong
 * @Date 2024/8/28 14:00
 * @Version 1.0.0
 */
public class ThreadCommunicationT04 {

    public static int sept = -1;
    public static String str = "1A2B3C4D";
    public static ReentrantLock lock = new ReentrantLock();
    public static Condition h = lock.newCondition();
    public static Condition d = lock.newCondition();


    public static void h(char[] chars, int index) throws Exception {
        lock.lock();
        try {
            System.out.print(Thread.currentThread().getName() + " : " );
            System.out.println(chars[index]);
            SleepingUtil.sleep(1, TimeUnit.SECONDS);
            d.signal();
            h.await();
        } finally {
            lock.unlock();
        }
    }

    public static void d(char[] chars, int index) throws Exception {
        lock.lock();
        try {
            System.out.print(Thread.currentThread().getName() + " : " );
            System.out.println(chars[index]);
            SleepingUtil.sleep(1, TimeUnit.SECONDS);
            h.signal();
            d.await();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        char[] chars = str.toCharArray();

        new Thread(() -> {
            while (true) {
                int index = getIndex(chars.length);
                try {
                    h(chars, index);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }


        }).start();

        new Thread(() -> {
            while (true) {
                int index = getIndex(chars.length);
                try {
                    d(chars, index);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }

    public static int getIndex(int size) {
        sept ++;
        if(sept == size) {
            sept = 0;
        }
        return sept;
    }

}
